package br.gov.ibama.client.visao.nota;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import br.gov.ibama.client.AuthService;
import br.gov.ibama.client.AuthServiceAsync;
import br.gov.ibama.client.componentes.BasisComponentes;
import br.gov.ibama.client.constantes.ConstantesDS;
import br.gov.ibama.client.constantes.ConstantesFields;
import br.gov.ibama.client.visao.VisaoPopup;

import com.google.gwt.core.client.GWT;
import com.smartgwt.client.data.Criteria;
import com.smartgwt.client.data.DSCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.ListGridEditEvent;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.ImgButton;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.fields.ComboBoxItem;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.form.validator.FloatRangeValidator;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;

public class VisaoPopupNota extends VisaoPopup{

	public static final AuthServiceAsync authService = GWT
			.create(AuthService.class);
	
	public VisaoPopupNota(String title) {
		super (title);
	}

	protected List<ImgButton> getBotoes (){
		List<ImgButton> listaBotoes = new ArrayList<ImgButton>();
		listaBotoes.add(getBotaoPesquisar());
		listaBotoes.add(getBotaoCancelar());
		return listaBotoes;
	}
	
	private ImgButton getBotaoPesquisar(){
		ImgButton Salvar = BasisComponentes.criaImgButton("Pesquisar", "pesquisar_48x48.png");
		Salvar.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				if (validaCampos()) {
					FormItem disciplina = getFormulario().getItem(ConstantesFields.FIELD_DISCIPLINA_TURMA);
					Criteria criteria = new Criteria();
					criteria.addCriteria(ConstantesFields.FIELD_DISCIPLINA_ID, disciplina.getValue().toString());
					DataSource.get(ConstantesDS.DS_NOTA).fetchData(criteria, new DSCallback() {
						
						@Override
						public void execute(DSResponse response, Object rawData, DSRequest request) {
							Record[] registros = response.getData();
							if (registros.length > 0) {

								Record registro = registros[0];
								VisaoPopup visao = new VisaoPopupFormularioNota("Cadastro das Notas");
								visao.redefinirTamanhoJanelaPopUp("450", "930", "880", "430");
								
								String disciplinaId = registro.getAttribute(ConstantesFields.FIELD_NOTA_DISCIPLINA_ID);
								Criteria criteria = new Criteria();
								criteria.addCriteria(ConstantesFields.FIELD_FREQUENCIA_DISCIPLINA_ID, disciplinaId);
								
							    final ListGrid frequenciaGrid = new ListGrid();  
						        frequenciaGrid.setWidth(850);  
						        frequenciaGrid.setHeight(430);  
						        frequenciaGrid.setShowAllRecords(true);  
						        frequenciaGrid.setCellHeight(22);  
						        frequenciaGrid.setCriteria(criteria);
						        frequenciaGrid.setDataSource(DataSource.get(ConstantesDS.DS_NOTA));  
						  	  
						        ListGridField codigo = new ListGridField(ConstantesFields.FIELD_NOTA_ID, "Código"); 
						        codigo.setWidth(50);	
						        codigo.setAlign(Alignment.CENTER);
						        ListGridField aluno = new ListGridField(ConstantesFields.FIELD_NOTA_ALUNO_NOME, "Aluno");
						        aluno.setWidth(150);
						        FloatRangeValidator rangeValidator = new FloatRangeValidator();
						        rangeValidator.setMin(0);
						        rangeValidator.setMax(10);
						        ListGridField NOTA_1 = new ListGridField(ConstantesFields.FIELD_NOTA_1, "Nota 1");
						        NOTA_1.setType(ListGridFieldType.FLOAT);
						        NOTA_1.setAlign(Alignment.CENTER);
						        NOTA_1.setDecimalPrecision(2);
						        NOTA_1.setValidators(rangeValidator);
						        ListGridField NOTA_2 = new ListGridField(ConstantesFields.FIELD_NOTA_2, "Nota 2");
						        NOTA_1.setType(ListGridFieldType.FLOAT);
						        NOTA_1.setAlign(Alignment.CENTER);
						        NOTA_1.setDecimalPrecision(2);
						        NOTA_1.setValidators(rangeValidator);
						        ListGridField NOTA_3 = new ListGridField(ConstantesFields.FIELD_NOTA_3, "Nota 3");
						        NOTA_1.setType(ListGridFieldType.FLOAT);
						        NOTA_1.setAlign(Alignment.CENTER);
						        NOTA_1.setDecimalPrecision(2);
						        NOTA_1.setValidators(rangeValidator);
						        ListGridField NOTA_4 = new ListGridField(ConstantesFields.FIELD_NOTA_4, "Nota 4");
						        NOTA_1.setType(ListGridFieldType.FLOAT);
						        NOTA_1.setAlign(Alignment.CENTER);
						        NOTA_1.setDecimalPrecision(2);
						        NOTA_1.setValidators(rangeValidator);
						        ListGridField NOTA_5 = new ListGridField(ConstantesFields.FIELD_NOTA_5, "Nota 5");
						        NOTA_1.setType(ListGridFieldType.FLOAT);
						        NOTA_1.setAlign(Alignment.CENTER);
						        NOTA_1.setDecimalPrecision(2);
						        NOTA_1.setValidators(rangeValidator);
						        ListGridField NOTA_6 = new ListGridField(ConstantesFields.FIELD_NOTA_6, "Nota 6");
						        NOTA_1.setType(ListGridFieldType.FLOAT);
						        NOTA_1.setAlign(Alignment.CENTER);
						        NOTA_1.setDecimalPrecision(2);
						        NOTA_1.setValidators(rangeValidator);
						        ListGridField NOTA_7 = new ListGridField(ConstantesFields.FIELD_NOTA_7, "Nota 7");
						        NOTA_1.setType(ListGridFieldType.FLOAT);
						        NOTA_1.setAlign(Alignment.CENTER);
						        NOTA_1.setDecimalPrecision(2);
						        NOTA_1.setValidators(rangeValidator);
						        ListGridField NOTA_8 = new ListGridField(ConstantesFields.FIELD_NOTA_8, "Nota 8");
						        NOTA_1.setType(ListGridFieldType.FLOAT);
						        NOTA_1.setAlign(Alignment.CENTER);
						        NOTA_1.setDecimalPrecision(2);
						        NOTA_1.setValidators(rangeValidator);
						        ListGridField NOTA_9 = new ListGridField(ConstantesFields.FIELD_NOTA_9, "Nota 9");
						        NOTA_1.setType(ListGridFieldType.FLOAT);
						        NOTA_1.setAlign(Alignment.CENTER);
						        NOTA_1.setDecimalPrecision(2);
						        NOTA_1.setValidators(rangeValidator);
						        ListGridField NOTA_10 = new ListGridField(ConstantesFields.FIELD_NOTA_10, "Nota 10");
						        NOTA_1.setType(ListGridFieldType.FLOAT);
						        NOTA_1.setAlign(Alignment.CENTER);
						        NOTA_1.setDecimalPrecision(2);
						        NOTA_1.setValidators(rangeValidator);
					        
						        frequenciaGrid.setFields(codigo, aluno, NOTA_1, NOTA_2, NOTA_3, NOTA_4, NOTA_5, 
						        		NOTA_6, NOTA_7, NOTA_8, NOTA_9, NOTA_10);  
						  
						        frequenciaGrid.setAutoFetchData(true);  
						        frequenciaGrid.setCanEdit(true);  
						        frequenciaGrid.setEditEvent(ListGridEditEvent.CLICK); 
						        
						        visao.addComponentes(frequenciaGrid);
						        						        								
						        visao.draw();
							} else {
								SC.warn("Não há notas cadastradas para essa disciplina!");
							}
						}
					});
				}
			}
		});
		return Salvar;
	}
		
	private ImgButton getBotaoCancelar(){
		ImgButton Cancelar = BasisComponentes.criaImgButton("Cancelar", "cancelar_32x32.png");
		Cancelar.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				destroy();
				
			}
		});
		return Cancelar;
	}
	
	public void criaFormulario(){
		preparaFormulario(ConstantesDS.DS_NOTA, getListaCamposFormulario());
	}
	
	public FormItem[] getListaCamposFormulario(){
		return getCamposFormulario().toArray(new FormItem[getCamposFormulario().size()]);
	}
	
	private List<FormItem> getCamposFormulario(){
	
		List<FormItem> listaCampos = new ArrayList<FormItem>();
		
		ComboBoxItem escola = BasisComponentes.criaComboboxObrigatorioGrande(ConstantesFields.FIELD_ESCOLA_NOME, "Nome da Escola");
		escola.setOptionDataSource(DataSource.get(ConstantesDS.DS_ESCOLA));
		escola.setDisplayField(ConstantesFields.FIELD_ESCOLA_NOME);
		escola.setValueField(ConstantesFields.FIELD_ESCOLA_ID);
		escola.addChangedHandler(new ChangedHandler() { 
            public void onChanged(ChangedEvent event) {  
            	getFormulario().clearValue(ConstantesFields.FIELD_DISCIPLINA_TURMA);
            	Integer selectedItem = (Integer) event.getValue(); 
				Criteria criteria = new Criteria();
				criteria.addCriteria(ConstantesFields.FIELD_ESCOLA_ID, selectedItem.toString());
				DataSource.get(ConstantesDS.DS_DISCIPLINA).fetchData(criteria, new DSCallback() {
					
					@Override
					public void execute(DSResponse response, Object rawData, DSRequest request) {
						LinkedHashMap mapaDasDisciplinas = new LinkedHashMap();
						if (!response.getDataAsRecordList().isEmpty() && response.getDataAsRecordList().getLength() > 0) {
							Record[] registros = response.getData();
							for (int i = 0; i < registros.length; i++) {
								Record registro = registros[i];
								String disciplinaID = registro.getAttribute(ConstantesFields.FIELD_DISCIPLINA_ID);
								String disciplinaTurma = registro.getAttribute(ConstantesFields.FIELD_DISCIPLINA_TURMA);
								String disciplinaNome = registro.getAttribute(ConstantesFields.FIELD_DISCIPLINA_NOME);
								mapaDasDisciplinas.put(disciplinaID, disciplinaTurma + " - " + disciplinaNome);
							}
						}
						getFormulario().getField(ConstantesFields.FIELD_DISCIPLINA_TURMA).setValueMap(mapaDasDisciplinas); 	
					}
				});
            }  
        });  
		listaCampos.add(escola);
		
		ComboBoxItem turma_disciplina = BasisComponentes.criaComboboxObrigatorioGrande(ConstantesFields.FIELD_DISCIPLINA_TURMA, "Turma");
		turma_disciplina.setAddUnknownValues(false);
        listaCampos.add(turma_disciplina);
        

		
		return listaCampos;		
	}
	
	private boolean validaCampos() {
		FormItem nomeEscola = getFormulario().getItem(ConstantesFields.FIELD_ESCOLA_NOME);
		FormItem turma = getFormulario().getItem(ConstantesFields.FIELD_DISCIPLINA_TURMA);
				
		// Verifica preenchimento dos campos obrigatórios
		if (isVazio(nomeEscola) || isVazio(turma)) {
			SC.warn("Há campos obrigatórios não preenchidos.");
			return false;
		}
		return true;
	}
	
	protected boolean isVazio(FormItem item){
		return item == null || item.getValue() == null || item.getValue().toString().equals("");	
	}
	
}
